package com.fashion.utils;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

/**
 * Created by IntelliJ IDEA.
 * User: keviyang
 * Date: 11-6-22
 * Time: 下午3:16
 */
public class DateConverter extends StrutsTypeConverter {

    private static String DATE_TIME_FOMART = "yyyy-MM-dd HH:mm:ss";
    private static String DATE_TIME_JSON_FOMART = "yyyy-MM-dd'T'HH:mm:ss";

    private static String DATE_FOMART = "yyyy-MM-dd";

    @Override
    public Object convertFromString(Map context, String[] values, Class toClass) {
        Date date = null;
        String dateString = null;
        if (values != null && values.length > 0) {
            dateString = values[0];
            if (dateString != null) {
                SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_FOMART);
                try {
                    date = format.parse(dateString);
                } catch (ParseException e) {
                    date = null;
                }
                if (date == null) {
                    try {
                        format = new SimpleDateFormat(DATE_TIME_JSON_FOMART);
                        date = format.parse(dateString);
                    } catch (ParseException e) {
                        date = null;
                    }
                }

                if (date == null) {
                    format = new SimpleDateFormat(DATE_FOMART);
                    try {
                        date = format.parse(dateString);
                    } catch (ParseException e) {
                        date = null;
                    }
                }
            }
        }
        return date;
    }

    @Override
    public String convertToString(Map arg0, Object arg1) {
        // TODO Auto-generated method stub
        return null;
    }
}
